﻿using System;
using System.IO;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Microsoft.VisualStudio.TextTemplating;
using T4Common;
using T4Common.Properties;

namespace CustomHost
{
    class Program
    {
        static void Main(string[] args)
        {
			Console.WriteLine(string.Format("代码输出目录:{0}", Settings.Default.ProjectRootPath));
			try
			{
				Console.WriteLine();
				Console.WriteLine("- - - - - - - - - - - - - - - - ");
				Console.WriteLine();
				string templateFolder = string.Format(@"{0}\Templates", Environment.CurrentDirectory);
				string[] files = Directory.GetFiles(templateFolder);
				for (int i = 0; i < files.Count(); i++)
				{
					if (Path.GetExtension(Path.GetFileName(files[i])) != ".tt")
						continue;
					Console.WriteLine(string.Format("模板{0}正在处理...", Path.GetFileName(files[i])));
					ProcessTemplate(files[i]);
				}
				Console.WriteLine();
				Console.WriteLine("- - - - - - - - - - - - - - - - ");
				Console.WriteLine();
				Console.WriteLine("模板全部处理完成,谢谢使用..");
				Console.Read();
			}
			catch (Exception ex)
			{
				Console.WriteLine(ex.Message);
			}
        }

        static void ProcessTemplate(params string[] args)
        {
            string templateFileName = null;

            if (args.Length == 0)
            {
                throw new System.Exception("you must provide a text template file path");
            }

            templateFileName = args[0];

            if (templateFileName == null)
            {
                throw new ArgumentNullException("the file name cannot be null");
            }

            if (!File.Exists(templateFileName))
            {
                throw new FileNotFoundException("the file cannot be found");
            }

            CustomCmdLineHost host = new CustomCmdLineHost();
            Engine engine = new Engine();

            host.TemplateFileValue = templateFileName;
          

            //Read the text template.
            string input = File.ReadAllText(templateFileName);
			input = input.Replace(@"$(ProjectDir)\", "");
            //Transform the text template.
            string output = engine.ProcessTemplate(input, host);

            string outputFileName = Path.GetFileNameWithoutExtension(templateFileName);
            outputFileName = Path.Combine(Path.GetDirectoryName(templateFileName), outputFileName);
            outputFileName = outputFileName + "1" + host.FileExtension;

            File.WriteAllText(outputFileName, output, host.FileEncoding);

            foreach (CompilerError error in host.Errors)
            {
                Console.WriteLine(error.ToString());
            }
        }

    }
}
